import * as SignalR from '@microsoft/signalr'
import { ElNotification } from 'element-plus'
import { logout } from '/@/api/sys'
import pinia from '/@/stores/index'
import { useAdminInfo } from '/@/stores/adminInfo'
import { Message } from '/@/api/sys/message'
import { useMessageInfo } from '/@/stores/messageInfo'
import { addDialog } from '../components/noticeDialog/index'
import globalConfig from '/@/utils/globalConfig'

let connection: SignalR.HubConnection

let baseURL: string = globalConfig.proxy?'':globalConfig.base_url;
const connectSignal = (token: string) => {
    const adminInfo = useAdminInfo(pinia)
    const messageInfo = useMessageInfo(pinia)
    if (!connection) {
        connection = new SignalR.HubConnectionBuilder()
            .configureLogging(SignalR.LogLevel.Information)
            .withUrl(
                `${baseURL}/hubs/Chat?access_token=${token}`
                //默认http模式，下面代码为websocket模式
                // {
                //     accessTokenFactory: () => token,
                //     skipNegotiation: true,
                //     transport: SignalR.HttpTransportType.WebSockets,
                // }
            )
            .withAutomaticReconnect({
                nextRetryDelayInMilliseconds: () => {
                    return 5000 // 每5秒重连一次
                },
            })
            .build()
        connection.keepAliveIntervalInMilliseconds = 15 * 1000 // 心跳检测15s
        connection.serverTimeoutInMilliseconds = 30 * 60 * 1000 // 超时时间30m
        connection.onclose(async () => {
            console.log('断开连接')
        })
        // 重连中
        connection.onreconnecting(() => {
            console.log('服务器已断线')
            ElNotification({
                title: '提示',
                message: '服务器已断线...',
                type: 'error',
                position: 'bottom-right',
            })
        })
        // 重连成功
        connection.onreconnected(() => {
            console.log('重连成功')
            ElNotification({
                title: '提示',
                message: '服务器重连成功...',
                type: 'success',
                position: 'bottom-right',
            })
        })
        //统一消息绑定地方
        connection.on('ForceOffline', (str: string) => {
            //调用注销接口
            logout()
                .then((res) => {
                    //断开连接
                    connection.stop()
                    //清空token
                    adminInfo.removeToken()
                    //刷新浏览器
                    window.location.reload()
                })
                .catch((res) => {})
                .finally(() => {})
            console.log(`强制退出操作,后端传参数${str}`)
        })
        connection.on('SendMessage', (message: Message) => {
            ElNotification({
                title: '提示',
                message: '你有一条新消息，可点击查看',
                type: 'success',
                position: 'bottom-right',
                //点击回调
                onClick: () => {
                    console.log('点击了')
                    console.log(message.title, message.message)
                    messageInfo.setMessage(message.message, message.message)
                    addDialog({
                        title: message.title,
                        width: '500px',
                        props: {
                            id: 0,
                        },
                        message: message.message,
                        component: null,
                        callBack: (data: any) => {
                            //当弹窗任务结束后，调用父页面的回掉函数。（比如我新增完成了需要刷新列表页面）
                            console.log('回调函数', data)
                        },
                    })
                },
            })
        })
    }
    connection.start().then(() => {
        console.log('signalr连接成功')
        // addDialog({
        //     title: '我是dialog,signalr连接成功',
        //     width: '500px',
        //     props: {
        //         id: 0,
        //     },
        //     component: null,
        //     callBack: (data: any) => {
        //         //当弹窗任务结束后，调用父页面的回掉函数。（比如我新增完成了需要刷新列表页面）
        //         console.log('回调函数', data)
        //     },
        // })
    })
}

export { connectSignal }
